import OSS from 'ali-oss';
import { getToken } from '@/services/common';
import { randomName, getExt } from '@/utils/index';
import { Message } from '@alicloudfe/components';
import config from './config';

interface IuploadType {
  file: File;
  dir?: string;
  type?: string;
  name?: string;
}

// 上传路径
const pathList = {
  user: 'userDir',
  org: 'orgDir',
  issue: 'issueDir',
  client: 'clientDir',
};

/**
 * oss上传
 * @param {
 *  file: 上传文件
 *  type: 上传类型：决定后端返回的上传目录 // user-用户 org-组织 issue-issue相关
 *  dir: 上传目录：dir存在时，优先使用此上传目录 // 正式环境使用后端返回目录，测试时可以使用此参数
 *  name: 上传文件名称（无后缀）
 * }
 * @returns
 */
const uploadFile = async ({ file, type = 'user', dir = '', name = randomName() }: IuploadType) => {
  try {
    const info = await getToken();
    const client = new OSS({
      region: info.ossRegionId,
      accessKeyId: info.accessKeyId,
      accessKeySecret: info.accessKeySecret,
      stsToken: info.securityToken,
      bucket: info.bucketName,
    });
    // filename = dir + name + ext
    const fileDir = dir || `${info[pathList[type]]}`;
    const filename = `${fileDir}${name}.${getExt(file.name)}`;
    const res = await client.put(filename, file);
    return {
      name: `/${res.name}`, // 表单提交项
      url: `${config.ossHost}/${res.name}`, // 预览图片地址
    };
  } catch (e) {
    if (e.code && e.code !== 200) {
      Message.warning(e.msg);
    }
    console.error('error: %j', e);
    return false;
  }
};

export default uploadFile;
